package cn.stylefeng.guns.modular.hx.storage.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.hx.storage.entity.TurnoverContainer;
import cn.stylefeng.guns.modular.hx.storage.service.TurnoverContainerDetailedService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.guns.modular.hx.storage.entity.TurnoverContainerDetailed;
import cn.stylefeng.guns.modular.hx.storage.mapper.TurnoverContainerDetailedMapper;
import cn.stylefeng.guns.modular.hx.storage.mapper.TurnoverContainerMapper;
import cn.stylefeng.guns.modular.hx.storage.model.params.TurnoverContainerParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.TurnoverContainerResult;
import  cn.stylefeng.guns.modular.hx.storage.service.TurnoverContainerService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 周转容器管理 服务实现类
 * </p>
 *
 * @author ZHDW
 * @since 2024-04-10
 */
@Service
public class TurnoverContainerServiceImpl extends ServiceImpl<TurnoverContainerMapper, TurnoverContainer> implements TurnoverContainerService {


    @Autowired
    private TurnoverContainerMapper turnoverContainerMapper;

    @Autowired
    private TurnoverContainerDetailedMapper turnoverContainerDetailedMapper;
    @Override
    public int t3(String packNumber) {

        return  turnoverContainerMapper.t3(packNumber);
    }

    @Resource
    private UserService userService;
    @Resource
    private BasicWarehouseService BasicWarehouseService ;

    @Override
    public ResponseData getExceldata(MultipartFile file, TurnoverContainerParam turnoverContainerParam, ResponseData data) throws IOException {
        User user = userService.getcurrentUser();
        turnoverContainerParam.setDeptId(user.getDeptId());
        turnoverContainerParam.setDeliverId(user.getDeliverId());

        if (ToolUtil.isEmpty(turnoverContainerParam.getWarehouseId())) {
            data.setSuccess(false);
            data.setMessage("请选择仓库");
            return data;
        }
        BasicWarehouse BasicWarehouse = BasicWarehouseService.getById(turnoverContainerParam.getWarehouseId());
        String fileName = file.getOriginalFilename();
        List<TurnoverContainer> list = new ArrayList<TurnoverContainer>();
        List<TurnoverContainerDetailed> listd = new ArrayList<TurnoverContainerDetailed>();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            TurnoverContainer turnoverContainerParam1 = new TurnoverContainer();
            TurnoverContainerDetailed createdd = new TurnoverContainerDetailed();
            createdd.setOperationType("初始化");
            createdd.setOperator(user.getName());
            createdd.setSendTime(new Date());
            createdd.setWarehouseId(turnoverContainerParam.getWarehouseId()+"");
            createdd.setWarehouseName(BasicWarehouse.getWarehouseName());
            createdd.setDeptId(user.getDeptId());
            createdd.setDeliverId(user.getDeliverId());

            turnoverContainerParam1.setStorageState("仓库");
            turnoverContainerParam1.setWarehouseName(BasicWarehouse.getWarehouseName());
            turnoverContainerParam1.setDeptId(user.getDeptId());
            turnoverContainerParam1.setDeliverId(user.getDeliverId());
            turnoverContainerParam1.setSendTime(new Date());
            turnoverContainerParam1.setOperator(user.getName());

            String  PackNumber = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(PackNumber)) {
                turnoverContainerParam1.setPackNumber(PackNumber);//容器编号
                createdd.setPackNumber(PackNumber);
                TurnoverContainer check = this.turnoverContainerService.lambdaQuery()
                        .eq(TurnoverContainer::getPackNumber,PackNumber)
                        .one();
                if(check != null){
                    continue;
                }
            }else{
                continue;
            }

            String  attribute = getCellValue(row.getCell(1));//类型
            if (ToolUtil.isNotEmpty(attribute)) {
                turnoverContainerParam1.setAttribute(attribute);
            }

            String  specifications = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(specifications)) {
                turnoverContainerParam1.setSpecifications(specifications);//规格
            }

            list.add(turnoverContainerParam1);
            listd.add(createdd);
        }
        if (list.size() > 0) {
            this.saveBatch(list);
            turnoverContainerDetailedService.saveBatch(listd);
        }
        data.setSuccess(true);
        return data;
    }

    @Resource
    private TurnoverContainerDetailedService turnoverContainerDetailedService;

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

    @Override
    public void add(TurnoverContainerParam param){
        if (t3(param.getPackNumber())>0){
            ResponseData.error("容器编号重复");
        }else {
            TurnoverContainer entity = getEntity(param);
            this.save(entity);
        }
    }


    @Override
    public void delete(TurnoverContainerParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(TurnoverContainerParam param){
        TurnoverContainer oldEntity = getOldEntity(param);
        TurnoverContainer newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public TurnoverContainerResult findBySpec(TurnoverContainerParam param){
        return null;
    }

    @Override
    public List<TurnoverContainerResult> findListBySpec(TurnoverContainerParam param){
        return null;
    }


    @Autowired
    private TurnoverContainerService turnoverContainerService;

    @Override
    public LayuiPageInfo findPageBySpec(TurnoverContainerParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }



    private Serializable getKey(TurnoverContainerParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private TurnoverContainer getOldEntity(TurnoverContainerParam param) {
        return this.getById(getKey(param));
    }

    private TurnoverContainer getEntity(TurnoverContainerParam param) {
        TurnoverContainer entity = new TurnoverContainer();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


}
